import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { Response } from './common/response';
import { HttpFilter } from './common/filter';
import { AllExceptionsFilter } from './common/any-exception.filter';
import { Logger } from '@nestjs/common';
import { logger } from './middleware/logger/logger.middleware';
import * as express from 'express';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import helmet from 'helmet';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  // 设置全局前缀
  app.setGlobalPrefix('admin');
  app.use(helmet());

  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));
  // 监听所有的请求路由，并打印日志
  app.use(logger);
  
  app.use((req, res, next) => {
    // 修改CSP（Content Security Policy）设置,允许iframe访问
    res.setHeader(
      'Content-Security-Policy',
      "frame-ancestors 'self' http://localhost:8080 http://localhost:8848 http://localhost:8100;",
    );
    //修改跨源资源策略，允许所有的源访问
    res.setHeader(
      'Cross-Origin-Resource-Policy','cross-origin'
    )
    next();
  });

  app.useGlobalInterceptors(new Response());
  app.useGlobalFilters(new HttpFilter());
  app.useGlobalFilters(new AllExceptionsFilter());
  // 静态资源目录共享，使用  /linxi  代替原始 join(__dirname, '../../images')  路径
  app.useStaticAssets(join(__dirname, '../../images'), {
    prefix: '/linxi',
  });
  const options = new DocumentBuilder()
    .setTitle('vue3-admin')
    .setVersion('1')
    .addBearerAuth()
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('/docs', app, document);
  await app.listen(9527, '0.0.0.0');
  const serverUrl = await app.getUrl();
  Logger.log(`api服务已经启动,请访问: ${serverUrl}`);
  Logger.log(`API文档已生成,请访问: ${serverUrl}/docs/`);
}
bootstrap();
